package com.example.hfut_edu;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.HandlerThread;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class page_login extends AppCompatActivity {

        public static page_login login_obj = null;
        private HandlerThread handlerThread;

        Button btn_zhuce,btn_denglu;
        TextView text_mail,text_passwd,textView_title;

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page_login);
        login_obj = this;
        Intent i = getIntent();  //直接获取传过来的intent
        String tempstr= i.getStringExtra("extra_data");
        text_mail =findViewById(R.id.text_mail);
        text_passwd =findViewById(R.id.text_passwd);
        textView_title=findViewById(R.id.textView_title);
        //btn_ljizhuce =findViewById(R.id.btn_lijizhuce);
        btn_denglu =findViewById(R.id.btn_denglu);
        //homepage.home_obg.finish()
            // MainActivity.main_obj.finish();
        textView_title.setText(tempstr);


            init();
            //--------------oncraete
        }


    private void init(){

        handlerThread = new HandlerThread("loginpage");
        handlerThread.start();
        final Handler handler = new Handler(handlerThread.getLooper());
        text_mail.setText(rwSPdata("r","jw_account",""));
        text_passwd.setText(rwSPdata("r","jw_passwd",""));

        //点击登陆
        btn_denglu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v1) {
                String account =text_mail.getText().toString();
                String passwd =text_passwd.getText().toString();
                timer.start();
                String denglu_url = "getuserdata?name=" + account + "&passwd=" + passwd;
                handler.post(new Runable_Task(denglu_url));
            }
        });

    }

    class Runable_Task implements Runnable {
        String API_URL;
        public Runable_Task(String API_URL) {
            this.API_URL = API_URL;
        }
        @Override
        public void run() {
            //耗时任务开始-----------------
            getdata_HTTP(API_URL);
            //----------------------------耗时任务结束
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerThread.quit();//停止Looper的循环
    }

    public void getdata_HTTP(String get_url) {

        String userdata;
        try {
            HttpURLConnection connection = null;
            try {

                Toast.makeText(page_login.this, "正在请求", Toast.LENGTH_SHORT).show();
                //URL url = new URL("https://iou.ink/file/temp/user.json");
                //URL url = new URL("http://155.94.158.151:23002/HFUTcourse/"+get_url);
                URL url = new URL("https://api.iou.ink/HFUTcourse/"+get_url);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");//设置访问方式为“GET”
                connection.setConnectTimeout(15000);//设置连接服务器超时时间为
                connection.setReadTimeout(15000);//设置读取服务器数据超时时间为

                if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                    //从服务器获取响应并把响应数据转为字符串打印
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while (null != (line = reader.readLine())) {
                        response.append(line);
                    }
                    userdata = response.toString();
                    //回传数据，转到课表
                    callBackFunc(userdata);
                }
            } catch (Exception e) {
                if (e.toString().contains("timeout")){
                    Toast.makeText(page_login.this, "请求超时，请检查教务系统是否正常", Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(page_login.this, e.toString(), Toast.LENGTH_LONG).show();
                }
                e.printStackTrace();
            } finally {
                if (null != connection) {
                    connection.disconnect();
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }



    CountDownTimer timer = new CountDownTimer(15000, 1000) {
        public void onTick(long millisUntilFinished) {
            btn_denglu.setEnabled(false);
            btn_denglu.setText("请等待" + millisUntilFinished / 1000 + "秒");
        }

        public void onFinish() {
            //Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            //startActivity(intent);
            btn_denglu.setEnabled(true);
            btn_denglu.setText("登陆");
        }
    };

    public String rwSPdata(String flag,String key,String value){
        //email,passwd,vrcode
        SharedPreferences testSP= getSharedPreferences("testSP", Activity.MODE_PRIVATE);
        switch (flag){
            case "w":
                SharedPreferences.Editor editor = testSP.edit();
                editor.putString( key, value );
                editor.apply();
                return "";
            case "r":
                return testSP.getString( key, "" );
            default:
                return "";
        }
    }

    public void callBackFunc(String data){
        if (data.contains("中文姓名")){
            rwSPdata("w","userdata",data);
            rwSPdata("w","islogin","True");
            String account =text_mail.getText().toString();
            String passwd =text_passwd.getText().toString();
            rwSPdata("w","jw_account", account);
            rwSPdata("w","jw_passwd", passwd);
            Toast.makeText(page_login.this, "请求成功", Toast.LENGTH_LONG).show();

            try {
                MainActivity.main_obj.finish();
                page_curriculum.curriculum_obj.finish();
                //page_settings.settings_obj.finish();
                //loginpage.login_obj.finish();
            }catch (Exception e){
                //Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
            }
            Intent intent=new Intent(this, MainActivity.class);
            startActivity(intent);
        }else if(data.contains("info")){
            Toast.makeText(page_login.this, "登陆失败，请检查账号密码,或者稍后再尝试登陆", Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(page_login.this, "登陆失败，未知错误", Toast.LENGTH_LONG).show();
        }
    }




}